# coding=utf-8

from rest_framework.decorators import action
from rest_framework.response import Response

from social.account.models import User
from social.feed.models import Post
from social.feed.serializers import PostSerializer
from social.search import logger
from social.search.models import EsUser, EsPost
from social.search.pagination import LimitOffsetPagination
from social.search.query import *
from social.user.serializers import SimpleUserSerializer, AVCallUserSerializer, HomeUserSerializer
from social.utils.views import BaseGenericViewSet, ListModelMixin


class SearchViewSet(BaseGenericViewSet, ListModelMixin):
    queryset = User.objects.all()
    pagination_class = LimitOffsetPagination

    def get_serializer_context(self):
        context = super(SearchViewSet, self).get_serializer_context()
        if self.action == 'nearby_users':
            context['include_location'] = True
        return context

    @action(methods=['GET'], detail=False, serializer_class=HomeUserSerializer)
    def nearby_users(self, request, *args, **kwargs):
        lat = float(request.query_params.get('lat', 0))
        lng = float(request.query_params.get('lng', 0))

        if lat == 0 or lng == 0:
            return Response(data={'list': [], "next": None})
        user = request.user
        if user and not request.GET.get('next'):
            user.update_location(lat, lng, save=True)
        try:
            _next_query = request.query_params.get('next', 0)
            if _next_query and int(_next_query) > 2000:
                return Response(data={'list': [], "next": None})
        except Exception as e:
            logger.error(f"NearbyInvalidNext:{str(e)}")

        query = NearbyUserQuery(lat, lng, gender=request.GET.get('gender'), role=request.GET.get('role'))
        self.queryset = EsUser.search().update_from_dict(query.to_query())
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        page = [x for x in page if str(x.meta.id) != str(request.user.id)]
        ids = [x.meta.id for x in page]
        users = User.objects.filter(id__in=ids)
        serializer = self.get_serializer(users, many=True)
        return self.get_paginated_response(serializer.data)

    @action(methods=['GET'], detail=False, serializer_class=HomeUserSerializer)
    def recommend_users(self, request, *args, **kwargs):
        target_gender = request.GET.get('gender')
        role = request.GET.get('role')
        query_builder = HotUserQuery(gender=target_gender, role=role, user_id=request.user.id)
        self.queryset = EsUser.search().update_from_dict(query_builder.to_query())
        self.queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(self.queryset)
        page = [x for x in page if str(x.meta.id) != str(request.user.id)]
        ids = [x.meta.id for x in page]
        users = User.objects.filter(id__in=ids)
        serializer = self.get_serializer(users, many=True, context={'request': request})
        return self.get_paginated_response(serializer.data)

    @action(methods=['GET'], detail=False, serializer_class=AVCallUserSerializer)
    def av_call_users(self, request, *args, **kwargs):
        gender = request.user.gender
        target_gender = "g" if gender == "b" else "b"
        query_builder = AVCallUserQuery(gender=target_gender, user_id=request.user.id)
        self.queryset = EsUser.search().update_from_dict(query_builder.to_query())
        self.queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(self.queryset)
        page = [x for x in page if str(x.meta.id) != str(request.user.id)]
        ids = [x.meta.id for x in page]
        users = User.objects.select_related('av_call_setting').filter(id__in=ids)
        serializer = self.get_serializer(users, many=True, context={'request': request})
        return self.get_paginated_response(serializer.data)

    @action(methods=['GET'], detail=False, serializer_class=PostSerializer)
    def recommend_posts(self, request, *args, **kwargs):
        gender = request.user.gender
        target_gender = "g" if gender == "b" else "b"
        query_builder = HotPostQuery(gender=target_gender, user_id=request.user.id)
        self.queryset = EsPost.search().update_from_dict(query_builder.to_query())
        self.queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(self.queryset)
        ids = [x.meta.id for x in page]
        posts = Post.objects.filter(id__in=ids)
        serializer = self.get_serializer(posts, many=True, context={'request': request})
        return self.get_paginated_response(serializer.data)
